<?
include_once "constants.php";

function query_db($query)
{
	// connect to mysql
	$link = mysql_connect(DB_HOST, DB_USER, DB_PASS)
		or die("Failed to connect to database server: " . mysql_error());
	
	// select our db
	mysql_select_db(DB)
		or die("Failed to select database on DB server: " . mysql_error());
		
	// execute
	$result = mysql_query($query);
	
	// close the link
	mysql_close($link);
	
	// return the result
	return $result;
}
function insert_db($query)
{
	// connect to mysql
	$link = mysql_connect(DB_HOST, DB_USER, DB_PASS)
		or die("Failed to connect to database server: " . mysql_error());
	
	// select our db
	mysql_select_db(DB)
		or die("Failed to select database on DB server: " . mysql_error());
		
	// execute
	mysql_query($query);
	
	$id = mysql_insert_id();
	
	// close the link
	mysql_close($link);
	
	// return the result
	return $id;
}

class DB {
	
	private $link;
	private $result;
	private $hasResult;
	
	public function __construct() {
		$link = null;
		$result = null;
		$hasResult = false;
	}
	
	/* connects to DB server and selects DB */
	public function connect() {
		$link = mysql_connect(DB_HOST, DB_USER, DB_PASS)
			or die("Failed to connect to database server: " . mysql_error());
		mysql_select_db(DB)
			or die("Failed to select database on DB server: " . mysql_error());
	}
	
	/* closes connection to DB server */
	public function close() {
		$this->free();
		mysql_close($link);
	}
	
	/* frees result memory */
	public function free() {
		if ($hasResult) {
			mysql_free_result($result);
			$hasResult = false;
		}
	}
	
	/* queries the DB
	$query SQL query as a string */
	public function query($query) {
		$this->free();
		$words = explode(" ", $query);
		$type = strtoupper($words[0]);
		$result = mysql_query($query) or die("query failed: " . mysql_error());
		if ($type == "SELECT") {
			$hasResult = true;
		}
	}
	
	/* returns number of rows in last result (0 if no result) */
	public function rows() {
		if ($hasResult) {
			return mysql_num_rows($result);
		}
		return 0;
	}
	
	/* returns number of rows affected by last query */
	public function affected() {
		return mysql_affected_rows();
	}
	
	/* returns auto-incremented ID of last query (if last query was INSERT */
	public function insertid() {
		return mysql_insert_id();
	}
	
	/* fetches the next row from the result of the previous query,
	returns the row as an associative array where the keys are the field names
	from the table in the DB, or false if there are no more rows */
	public function nextRow() {
		if ($hasResult) {
			return mysql_fetch_array($result, MYSQL_ASSOC);
		} else {
			return false;
		}
	}
	
}

?>